$(function () {
  // wzERP.Contract.init();
  // wzERP.Contract.turnPage();//分页
  wzERP.Common.inlineDate('#date1', '#date2');  //联动日期

});
//表单模板数据请求
//删除左右两端的空格
function blankSpace(str){
    return str.replace(/(^\s*)|(\s*$)/g, "")
}
//验证规则
var file = {}
file.checkform = function (ele) {
  /*Arg Guide
   @ ele 要验证的表单
   */
  $(ele).form('submit');
  return $(ele).hasClass('error');
}
file.verifier = function (_selector) {
  /*Arg Guide
   @_selector: 对象选择器
   */
  $(_selector).form({
    on: 'blur',
    transition: 'fade',
    fields: {
      //客户名称
      customerName: {
        identifier: 'custIdS',
        rules: [{
          type: 'empty',
          prompt: '请输入客户名称'
        }]
      },
      //签单日期
      signingTime: {
        identifier: 'signOrderDate',
        rules: [{
          type: 'empty',
          prompt: '请选签单日期'
        }]
      },
    }
  });

};
file.verifier('.file-verifier');//开启验证功能
demo(1)
// 获取当前页面内容
function demo(curr, num, searchKey, startDate, endDate) {
  //curr:当前页
  //num:每页显示条数
  //searchKey:搜索内容
  //startDate:开始时间
  //endDate:结束时间
  $.get('/order/offline/queryByPage', {
    current: curr || 1,
    pageSize: num || 10,
    searchKey: searchKey,
    startDate: startDate,
    endDate: endDate
  }, function (data) {
    //获取内容显示到模板上
    if (data.code == 9999) {
      // debugger
      layer.msg(data.msg, {time: 1000});
      wzERP.Common.TimeoutLogin();
      return false;
    }
    var content = data
    $.get('/account/queryAccountDetail', function (data) {
      if (data.code == 9999) {
        // debugger
        layer.msg(data.msg, {time: 1000});
        wzERP.Common.TimeoutLogin();
        return false;
      }
      for (var i = 0; i < content.data.records.length; i++) {
        content.data.records[i].companyCodes = data.data.companyCode
      }
      $('#LinelistAreaData').html(template('LinelistArea', content.data))
      $('.recordOne').text(content.data.total)
      $('.recordTwo').text(content.data.pages)
      console.log(content)
      permissonHandler();
      // 分页
      layui.use(['laypage', 'layer'], function () {
        var laypage = layui.laypage;
        laypage({
          cont: 'turn-page',
          curr: curr || 1,
          pages: content.data.pages,
          skin: '#457fe6',
          skip: true,
          jump: function (obj, first) {
            var num = $('#LinenumberOf select').val()
            if (!first) {
              demo(obj.curr, num);
            }
          }
        });
      });
    })
  })
}
//获取时间和内容方法和当前页，每页显示条数，客户ID
function timeS() {
  var timeA = {}
  // 获取表单时间
  var content = $("#LinesearchForm").serialize()
  //使用方法分割取出
  var contentS = content.split('&')
  var obj = {}
  for (var i = 0; i < contentS.length; i++) {
    var con = contentS[i].toString()
    var son = con.split('=')
    obj[son[0]] = son[1]
  }
  //获取当前每页应该显示条数
  timeA.num = $('#LinenumberOf select').val()
  //获取搜索框内容
  timeA.searchKey =blankSpace($('#LinesearchKeyA').val())
  //获取分割好的起止时间
  timeA.startDate = obj.startDate
  timeA.endDate = obj.endDate
  //当前页
  timeA.page = $('.layui-laypage-skip').val()
  return timeA
}
//刷新当前页方法
function queryS(curr, num, searchKey, startDate, endDate, name) {
  //curr:当前页
  //num:每页显示条数
  //searchKey:搜索内容
  //startDate:开始时间
  //endDate:结束时间
  //name客户ID

  $.get('/order/offline/queryByPage', {
    current: curr || 1,
    pageSize: num || 10,
    searchKey: searchKey,
    startDate: startDate,
    endDate: endDate,
    custId: name
  }, function (data) {
    //获取内容显示到模板上
    if (data.code == 9999) {
      // debugger
      layer.msg(data.msg, {time: 1000});
      wzERP.Common.TimeoutLogin();
      return false;
    }
    var content = data
    $.get('/account/queryAccountDetail', function (data) {
      for (var i = 0; i < content.data.records.length; i++) {
        content.data.records[i].companyCodes = data.data.companyCode
      }
      $('#LinelistAreaData').html(template('LinelistArea', content.data))
      $('.recordOne').text(content.data.total)
      $('.recordTwo').text(content.data.pages)
      console.log(content)
      // 分页
      layui.use(['laypage', 'layer'], function () {
        var laypage = layui.laypage;
        laypage({
          cont: 'turn-page',
          curr: curr || 1,
          pages: content.data.pages,
          skin: '#457fe6',
          skip: true,
          jump: function (obj, first) {
            if (!first) {
              //获取客户ID
              $.get('/customer/queryKVList', function (data) {
                if (data.code == 9999) {
                  // debugger
                  layer.msg(data.msg, {time: 1000});
                  wzERP.Common.TimeoutLogin();
                  return false;
                }
                if ($('#customerContent').val() != '') {
                  var val
                  var name = $('#customerContent').val()
                  for (var i = 0; i < data.data.length; i++) {
                    if (data.data[i].value == name) {
                      val = data.data[i].key
                    }
                  }
                } else {
                  var val = null
                }
                var timeA = timeS()
                //获取当前每页应该显示条数
                queryS(obj.curr, timeA.num, timeA.searchKey, timeA.startDate,
                    timeA.endDate, val)
              })

            }
          }
        });
      });
    })
  })
}
//渲染搜索客户
$('#customerContent').on('keyup', function () {
  $.get('/customer/queryKVList', function (data) {
    if (data.code == 9999) {
      // debugger
      layer.msg(data.msg, {time: 1000});
      wzERP.Common.TimeoutLogin();
      return false;
    }
    console.log(data.data)
    var content = []
    var description = []
    for (var i = 0; i < data.data.length; i++) {
      content.push({title: data.data[i].value})
    }
    console.log(description)
    $('#customerSearch').search({
      source: content,
    })
  })
})
// 每页显示条数
$('#LinenumberOf ').on('click', function () {
  //获取当前页数
  var page = $('.layui-laypage-skip').val()
  // 获取表单时间
  var content = $("#LinesearchForm").serialize()
  //使用方法分割取出
  var contentS = content.split('&')
  var obj = {}
  for (var i = 0; i < contentS.length; i++) {
    var con = contentS[i].toString()
    var son = con.split('=')
    obj[son[0]] = son[1]
  }
  //获取当前每页应该显示条数
  var num = $('#LinenumberOf select').val()
  //获取搜索框内容
  var searchKey = blankSpace($('#LinesearchKeyA').val())
  //获取分割好的起止时间
  var startDate = obj.startDate
  var endDate = obj.endDate
  demo(page, num, searchKey, startDate, endDate)
})

//查询业务
$("#LinetimeA").on('click', function () {
  // 获取表单时间
  var content = $("#LinesearchForm").serialize()
  //使用方法分割取出
  var contentS = content.split('&')
  var obj = {}
  for (var i = 0; i < contentS.length; i++) {
    var con = contentS[i].toString()
    var son = con.split('=')
    obj[son[0]] = son[1]
  }
  //获取当前每页应该显示条数
  var num = $('#LinenumberOf select').val()
  //获取搜索框内容
  var searchKey = blankSpace($('#LinesearchKeyA').val())
  //获取分割好的起止时间
  var startDate = obj.startDate
  var endDate = obj.endDate
  //客户ID
  var val
  if ($('#customerContent').val() == '') {
    query(1, num, searchKey, startDate, endDate, null)
  } else {
    $.get('/customer/queryKVList', function (data) {
      var name = $('#customerContent').val()
      for (var i = 0; i < data.data.length; i++) {
        if (data.data[i].value == name) {
          val = data.data[i].key
        }
      }
      if (val == undefined) {
        layer.msg('客户不存在', {icon: 5})
      }
      query(1, num, searchKey, startDate, endDate, val)
    })
  }
  //获取搜索内容
  function query(curr, num, searchKey, startDate, endDate, name) {
    $.get('/order/offline/queryByPage', {
      current: curr || 1,
      pageSize: num || 10,
      searchKey: searchKey,
      startDate: startDate,
      endDate: endDate,
      custId: name
    }, function (data) {
      //获取内容显示到模板上
      if (data.code == 9999) {
        // debugger
        layer.msg(data.msg, {time: 1000});
        wzERP.Common.TimeoutLogin();
        return false;
      }
      var content = data
      $.get('/account/queryAccountDetail', function (data) {
        for (var i = 0; i < content.data.records.length; i++) {
          content.data.records[i].companyCodes = data.data.companyCode
        }
        $('#LinelistAreaData').html(template('LinelistArea', content.data))
        $('.recordOne').text(content.data.total)
        $('.recordTwo').text(content.data.pages)
        console.log(content)
        // 分页
        layui.use(['laypage', 'layer'], function () {
          var laypage = layui.laypage;
          laypage({
            cont: 'turn-page',
            curr: curr || 1,
            pages: content.data.pages,
            skin: '#457fe6',
            skip: true,
            jump: function (obj, first) {
              if (!first) {
                //获取客户ID
                $.get('/customer/queryKVList', function (data) {
                  if (data.code == 9999) {
                    // debugger
                    layer.msg(data.msg, {time: 1000});
                    wzERP.Common.TimeoutLogin();
                    return false;
                  }
                  if ($('#customerContent').val() != '') {
                    var val
                    var name = $('#customerContent').val()
                    for (var i = 0; i < data.data.length; i++) {
                      if (data.data[i].value == name) {
                        val = data.data[i].key
                      }
                    }
                  } else {
                    var val = null
                  }
                  var timeA = timeS()
                  //获取当前每页应该显示条数
                  query(obj.curr, timeA.num, timeA.searchKey, timeA.startDate,
                      timeA.endDate, val)
                })
              }
            }
          });
        });
      })
    })
  }

  return false
})

//添加订单
//订单客户事件
var content = []
setTimeout(function () {
    $.get('/customer/queryKVList',function (data) {
        for (var i = 0; i < data.data.length; i++) {
            content.push({title: data.data[i].value})
        }
    })
},3000)
$('#LineOrderPlaceA').on('keyup', '#custId', function () {
    var str = $('#custId').val()
    if(str==''){
      return false
    }
    $('#addClient').search({
        source: content
    })
    $.get('/customer/queryKVList',{ searchKey: str },function (data) {
        if (data.code == 9999) {
            // debugger
            layer.msg(data.msg, {time: 1000});
            wzERP.Common.TimeoutLogin();
            return false;
        }
    })
})

//点击添加订单
$('#lineAddTo').on('click', function () {
  $('#LineAddToModal').modal({
    closable: false,
    transition: 'fade'
  }).modal('show')
  $('#LineOrderPlaceB .addRows').remove()
  $('#LineOrderPlaceB tr td.calculation').text('')
  $('#addButtonS').html(template('addButton'))
  $('#transformation').text('添加订单')
  addOrder()
  linkage()
  select()
  notAll()
  Total()
  $('#clickA').on('click', function () {
    $('.addRows').remove()
  })
  $('#clickB').on('click', function () {
    $('.addRows').remove()
  })
  //订单按键事件
  $('#LineOrderPlaceA').on('keyup', '#orderSearch', function () {
    var searchKey = $(this).val()
    $.get('/order/contract/queryKVList', {searchKey: searchKey},
        function (data) {
          if (data.code == 9999) {
            // debugger
            layer.msg(data.msg, {time: 1000});
            wzERP.Common.TimeoutLogin();
            return false;
          }
          console.log(data.data)
          var content = []
          for (var i = 0; i < data.data.length; i++) {
            content.push({title: data.data[i].value})
          }
          console.log(content)
          $('#drop-down').search({
            source: content
          })

        })
  })
})
//点击添加订单方法
function addOrder() {
  /*
   * 客户名称 customer
   * 订单编号(合同)order
   * 请选择员工staff
   * sku服务列表service
   * 服务top分类classification
   * */
  var customer
  var order
  //获取客户名称
  $.get('/customer/queryKVList', function (data) {
    if (data.code == 9999) {
      // debugger
      layer.msg(data.msg, {time: 1000});
      wzERP.Common.TimeoutLogin();
      return false;
    }
    customer = data.data
    //获取登录信息
    $.get('/account/queryAccountDetail', function (data) {
      var employId = data.data.employId
      var companyId = data.data.companyId
      //获取当前公司人员
      $.get('/basedata/employee/queryListByCompayID',
          {companyId: companyId}, function (data) {
            order = data.data
            var dataA = {
              customer: customer,
              order: order
            }
            for (var i = 0; i < order.length; i++) {
              order[i].signId = employId
            }
            //渲染客户名称,签单人
            $('#LineOrderPlaceA').html(template('LineAddTemplate', dataA))

            file.verifier('#LineOrderPlaceA .file-verifier');

            $('#LineOrderPlaceA #signOrderId').dropdown('restore defaults')
            $('#LineOrderPlaceA #talkOrderId').dropdown('restore defaults')
            console.log(dataA)
            wzERP.Common.singleDate('#date3')
            //判断优惠方式
            $('input[name="couponStatus"]').on('click', function () {
              var sval = $('input[name="couponStatus"]:checked').val()
              if (sval == 0) {
                $('#coupon').addClass("coupon")
                $('#wechat').addClass("coupon")
              } else if (sval == 1) {
                $('#coupon').removeClass("coupon")
                $('#wechat').addClass("coupon")
              } else if (sval == 2) {
                $('#coupon').addClass("coupon")
                $('#wechat').removeClass("coupon")
              }
            })
          })
    })
  })
}
//设置服务分类的三级联动
function linkage() {
  $('#LineOrderPlace').on('click', '#LineService', function () {
    $('#LineSelectionService').css('display', 'block')
    //一级联动
    $.get('/basedata/erpServiceClass/queryKVList', function (data) {
      if (data.code == 9999) {
        // debugger
        layer.msg(data.msg, {time: 1000});
        wzERP.Common.TimeoutLogin();
        return false;
      }
      $('#LineSelectionContentA').html(template('LineServiceTemplate', data))
      $('#serviceOne').on('change', function () {
        if ($('#serviceOne').val() == '') {
          $('#serviceTwo').addClass('classification')
          $('#serviceThree').addClass('classification')
          $('#serviceThree').val('')
          $('#serviceTwo').val('')
          return false
        }
        //二级联动
        $.get('/basedata/erpServiceClass/queryKVList',
            {parentId: $('#serviceOne').val()}, function (data) {
              if (data.code == 9999) {
                // debugger
                layer.msg(data.msg, {time: 1000});
                wzERP.Common.TimeoutLogin();
                return false;
              }
              if (data.data.length == 0) {
                $('#serviceTwo').addClass('classification')
                $('#serviceThree').addClass('classification')
                $('#serviceTwo').val('')
                $('#serviceThree').val('')
                return false
              } else {
                $('#serviceTwo').removeClass('classification')
              }
              var options = '<option value="">请选择</option>'
              var len = data.data.length;
              for (var i = 0; i < len; i++) {
                options += '<option value="' + data.data[i].key + '">'
                    + data.data[i].value + '</option>';
              }
              $('#serviceTwo').html(options);
              $('#serviceTwo').on('change', function () {
                if ($('#serviceTwo').val() == '') {
                  $('#serviceThree').addClass('classification')
                  $('#serviceThree').val('')
                  console.log($('#serviceTwo').val())
                  return false
                }
                //三级联动
                $.get('/basedata/erpServiceClass/queryKVList',
                    {parentId: $('#serviceTwo').val()}, function (data) {
                      if (data.code == 9999) {
                        // debugger
                        layer.msg(data.msg, {time: 1000});
                        wzERP.Common.TimeoutLogin();
                        return false;
                      }
                      console.log(data.data.length)
                      if (data.data.length == 0) {
                        $('#serviceThree').addClass('classification')
                      } else {
                        $('#serviceThree').removeClass('classification')
                      }
                      var options = '<option value="">请选择</option>'
                      var len = data.data.length;
                      for (var i = 0; i < len; i++) {
                        options += '<option value="' + data.data[i].key + '">'
                            + data.data[i].value + '</option>';
                      }
                      $('#serviceThree').html(options);
                    })
              })
            })
      })
    })
    servicePagingA(1)
    function servicePagingA(current) {
      $.get('/basedata/erpSkuDetail/queryPageList', {current: current},
          function (data) {
            if (data.code == 9999) {
              // debugger
              layer.msg(data.msg, {time: 1000});
              wzERP.Common.TimeoutLogin();
              return false;
            }
            //获取内容显示到模板上
            $('#LineSelectionContentB').html(
                template('LineStitleTemplate', data.data))
            // 分页
            layui.use(['laypage', 'layer'], function () {
              var laypage = layui.laypage;
              laypage({
                cont: 'turn-pageA',
                curr: current || 1,
                pages: data.data.pages,
                skin: '#457fe6',
                skip: true,
                jump: function (obj, first) {
                  if (!first) {
                    servicePagingA(obj.curr)
                  }
                }
              });
            });
          })
    }

    $('#LineSelectionContent').on('click', '#serviceBt', function () {
      servicePaging(1)
      function servicePaging(current) {
        $('#serviceForm').ajaxSubmit({
          data: {current: current}, success: function (data) {
            if (data.code == 9999) {
              // debugger
              layer.msg(data.msg, {time: 1000});
              wzERP.Common.TimeoutLogin();
              return false;
            }
            //获取内容显示到模板上
            $('#LineSelectionContentB').html(
                template('LineStitleTemplate', data.data))
            // 分页
            layui.use(['laypage', 'layer'], function () {
              var laypage = layui.laypage;
              laypage({
                cont: 'turn-pageA',
                curr: current || 1,
                pages: data.data.pages,
                skin: '#457fe6',
                skip: true,
                jump: function (obj, first) {
                  if (!first) {
                    servicePaging(obj.curr)
                  }
                }
              });
            });
          }
        })
      }

      return false
    })
  })
}
//设置全选和不全选
function select() {
  $('#LineSelectionContentB').on('click', '#btn1', function () {
    $('input[name="sku"]').prop("checked", this.checked);
  });
}
//设置全选和不全选
function notAll() {
  $('#LineSelectionContentB').on('click', '.skuA', function () {
    $('#btn1').prop("checked",
        $('.skuA').length == $(".skuA:checked").length ? true : false);
  })
}
//渲染表单和计算属性
$('#LineServiceForm').on('click', function () {
  $('#LineSelectionService').css('display', 'none')
  var chk_value = [];
  $('input[name="sku"]:checked').each(function () {
    chk_value.push($(this).val());
  });
  NetUtis.doPostBodySimple('/basedata/erpSkuDetail/queryListByIds',
      chk_value, function (data) {
        if (data.code == 9999) {
          // debugger
          layer.msg(data.msg, {time: 1000});
          wzERP.Common.TimeoutLogin();
          return false;
        }
        console.log(data.data)
        var arry = []
        $('#LineOrderPlaceB #valueId').each(function () {
          arry.push($(this).attr('data-id'))
        })
        for (var i = 0; i < data.data.length; i++) {
          for (var j = 0; j < arry.length; j++) {
            if (data.data[i].id == arry[j]) {
              data.data.splice(i, 1)
            }
          }
        }
        $('#LineOrderPlaceB').prepend(template('LineAddFormTemplate', data))
        //删除按钮
        $('#LineOrderPlaceA').on('click', '#delDT', function () {
          if ($('tr input[name="boxA"]:checked').length == $(
                  'tr input[name="boxA"]').length) {
            layer.msg('不能全部删除，请至少保留一条数据', {icon: 1})
          } else {
            $('tr input[name="boxA"]:checked').parents('.fods').remove();
          }
          calculation()
          //循环首期费用
          var downpayment = ''
          $('.downpayment').each(function () {
            downpayment += (+($(this).val()))
          })
          $('#paymentNum').text(downpayment)
        })
        //计算
        calculation()
        function calculation() {
          var quantityAnd = 0
          var Total = 0
          //循环添加数量
          $('#LineOrderPlaceB .subtractA').each(function () {
            quantityAnd += (+($(this).val()))
          });
          //循环添加总价
          $('#LineOrderPlaceB #aggregate').each(function () {
            Total += (+($(this).text()))
          });
          //优惠金额
          var Discount = $('#Discount').val() != 'null' ? $('#Discount').val()
              : 0
          //微商城金额
          var discountA = $('#discountA').val() != 'null' ? $(
              '#discountA').val() : 0

          //计算订单总额
          var num = Total - Discount - discountA
          //添加合计数量
          $('#quantityAnd').text(quantityAnd)
          //添加合计总价
          $('#Total').text(Total)
          //添加订单总额
          $('#LineOrderPlaceA #totalOrder').text(num)
          //数量变化时的总价
          $('#LineOrderPlaceB').on('change', '.subtractA', function () {
            //获取数量
            var numZ = $(this).val()
            //获取系列
            var seriesZ = $(this).parent().next().children(".subtractB").val()
            //附加成本
            var additionalCost = $(this).attr('data-cost') / 100
            //附加市场价
            var additionalMarketPrice = $(this).attr('data-price') / 100
            //附加官费
            var additionalOfficialExpenses = $(this).attr('data-expenses') / 100
            //单价
            var marketPriceZ = $(this).attr('data-priceA') / 100
            //渲染单价
            $(this).parent().siblings('.nnitSeries').text(
                marketPriceZ + ((+additionalCost) + (+additionalMarketPrice)
                + (+additionalOfficialExpenses)) * (seriesZ - 1))
            //计算总价
            var totalZ = numZ * (marketPriceZ + ((+additionalCost)
                + (+additionalMarketPrice) + (+additionalOfficialExpenses))
                * (seriesZ - 1))
            $(this).parent().siblings('#aggregate').text(totalZ)
            var quantityAndZ = 0
            var TotalZ = 0
            //循环添加数量
            $('#LineOrderPlaceB .subtractA').each(function () {
              quantityAndZ += (+($(this).val()))
            });
            //循环添加总价
            $('#LineOrderPlaceB #aggregate').each(function () {
              TotalZ += (+($(this).text()))
            });
            //优惠金额
            var DiscountZ = $('#Discount').val() != 'null' ? $(
                '#Discount').val() : 0
            //微商城金额
            var discountAZ = $('#discountA').val() != 'null' ? $(
                '#discountA').val() : 0
            //计算订单总额
            var numZ = TotalZ - DiscountZ - discountAZ
            //添加合计数量
            $('#quantityAnd').text(quantityAndZ)
            //添加合计总价
            $('#Total').text(TotalZ)
            //添加订单总额
            $('#LineOrderPlaceA #totalOrder').text(numZ)
          })
          //系列变化时的总价
          $('#LineOrderPlaceB').on('change', '.subtractB', function () {
            //获取系列
            var numW = $(this).val()
            //获取数量
            var seriesW = $(this).parent().prev().children(".subtractA").val()
            //附加成本
            var additionalCostW = $(this).attr('data-cost') / 100
            //附加市场价
            var additionalMarketPriceW = $(this).attr('data-price') / 100
            //附加官费
            var additionalOfficialExpensesW = $(this).attr('data-expenses')
                / 100
            //单价
            var marketPriceW = $(this).attr('data-priceA') / 100
            //渲染单价
            $(this).parent().siblings('.nnitSeries').text(
                marketPriceW + ((+additionalOfficialExpensesW)
                + (+additionalCostW) + (+additionalMarketPriceW)) * (numW - 1))
            //计算总价
            var totalW = seriesW * (marketPriceW
                + ((+additionalOfficialExpensesW) + (+additionalCostW)
                + (+additionalMarketPriceW)) * (numW - 1))
            $(this).parent().siblings('#aggregate').text(totalW)
            var quantityAndW = 0
            var TotalW = 0
            //循环添加数量
            $('#LineOrderPlaceB .subtractA').each(function () {
              quantityAndW += (+($(this).val()))
            });
            //循环添加总价
            $('#LineOrderPlaceB #aggregate').each(function () {
              TotalW += (+($(this).text()))
            });
            //优惠金额
            var DiscountW = $('#Discount').val() != 'null' ? $(
                '#Discount').val() : 0
            //微商城金额
            var discountAW = $('#discountA').val() != 'null' ? $(
                '#discountA').val() : 0
            //计算订单总额
            var numW = TotalW - DiscountW - discountAW
            //添加合计数量
            $('#quantityAnd').text(quantityAndW)
            //添加合计总价
            $('#Total').text(TotalW)
            //添加订单总额
            $('#LineOrderPlaceA #totalOrder').text(numW)
          })
          //计算首期费用
          $('#LineOrderPlaceB').on('change', '.downpayment', function () {
            //循环首期费用
            var downpayment = 0
            $('.downpayment').each(function () {
              downpayment += (+($(this).val()))
            })
            $('#paymentNum').text(downpayment)
          })
        }
      }, true);
})
//数量价格变化
//点击计算订单总额
function Total() {
  $('#LineOrderPlaceA').on('click', '.fruitB', function () {
    //判断选择的优惠
    if ($('input[name="couponStatus"]:checked').val() == 0) {
      //清空所有的金额
      $('#Discount').val('')
      $('#discountA').val('')
      $('input[name="voucherCode"]').val('')
      $('input[name="wechatMallName"]').val('')
      $('input[name="wechatMallOrder"]').val('')
      $('#LineOrderPlaceA #totalOrder').text('0')
      var Total = 0
      // 获取合计总额
      $('#LineOrderPlaceB #aggregate').each(function () {
        Total += (+($(this).text()))
      });
      var num = Total
      //添加合计总额
      $('#Total').text(num)
      //添加订单总额
      $('#LineOrderPlaceA #totalOrder').text(num)
      //判断选择的优惠
    } else if ($('input[name="couponStatus"]:checked').val() == 1) {
      //清空订单总额
      $('#LineOrderPlaceA #totalOrder').text('0')
      //清空商城优惠金额
      $('#discountA').val('')
      $('input[name="wechatMallName"]').val('')
      $('input[name="wechatMallOrder"]').val('')
      var Total = 0
      // 获取合计总额
      $('#LineOrderPlaceB #aggregate').each(function () {
        Total += (+($(this).text()))
      });
      var num = Total
      //添加合计总额
      $('#Total').text(num)
      //添加订单总额
      $('#LineOrderPlaceA #totalOrder').text(num)
      //判断优惠金额的变化
      $('#LineOrderPlaceA').on('change', '#Discount', function () {
        var Total = 0
        //获取优惠金额
        var Discount = $(this).val() != 'null' ? $(this).val() : 0
        //获取合计总额
        $('#LineOrderPlaceB #aggregate').each(function () {
          Total += (+($(this).text()))
        });
        //减去优惠金额
        var num = Total - Discount
        //添加订单总额
        $('#LineOrderPlaceA #totalOrder').text(num)
      })
      //判断选择的优惠
    } else if ($('input[name="couponStatus"]:checked').val() == 2) {
      //清空订单总额
      $('#LineOrderPlaceA #totalOrder').text('0')
      //清空优惠金额
      $('#Discount').val('')
      $('input[name="voucherCode"]').val('')
      var Total = 0
      //获取合计总额
      $('#LineOrderPlaceB #aggregate').each(function () {
        Total += (+($(this).text()))
      });
      var num = Total
      //添加订单总额
      $('#LineOrderPlaceA #totalOrder').text(num)
      //判断优惠金额的变化
      $('#LineOrderPlaceA').on('change', '#discountA', function () {
        var Total = 0
        //获取商城优惠金额
        var Discount = $(this).val() != 'null' ? $(this).val() : 0
        //获取合计总额
        $('#LineOrderPlaceB #aggregate').each(function () {
          Total += (+($(this).text()))
        });
        //减去商城优惠金额
        var num = Total - Discount
        //添加订单总额
        $('#LineOrderPlaceA #totalOrder').text(num)
      })
    }
  })
}
//添加订单内容
//添加合同
$('#addButtonS').on('change', '#file', function () {
  if (!$('#file').val().endsWith('pdf')) {
    layer.msg('合同格式错误', {icon: 5})
    return false
  }
  $('#files').ajaxSubmit({
    data: {type: 1},
    success: function (data) {
      if (data.code == 0) {
        layer.msg('上传成功', {icon: 7})
        $('#addButtonS').html(template('addButton', data.data))
      }
      else if (data.code == 9999) {
        // debugger
        layer.msg(data.msg, {time: 1000});
        wzERP.Common.TimeoutLogin();
      }
      else {
        layer.msg('上传失败', {icon: 5})
      }
    }
  })
})
//只能输入1到100的数字
var preValue = '';
var preValueA = '';
//数量
$("#LineAddToModal").on("keyup", "input[name=number]", function () {
  var value = $(this).val();
    if(value==''){
    $(this).val('')
    return false
    }
  if (!!value && !$(this).val().match(/(^[1-9][0-9]$)|(^100&)|(^[1-9]$)$/)) {
    $(this).val(preValue);
    return false;
  }
  preValue = $(this).val();
  return true;
});
//系列数量
$("#LineAddToModal").on("keyup", "input[name=seriesNum]", function () {
  var value = $(this).val();
    if(value==''){
        $(this).val('')
        return false
    }
  if (!!value && !$(this).val().match(/^([1-9]\d?|100)$/)) {
    $(this).val(preValueA);
    return false;
  }
  preValueA = $(this).val();
  return true;
});
//首期费用数量
$("#LineAddToModal").on("keyup", ".downpayment", function () {
  var value = $(this).val();
  if (!!value && !$(this).val().match(/^[0-9]*$/)) {
    $(this).val(preValueA);
    return false;
  }
  preValueA = $(this).val();
  return true;
});
//优惠金额
$("#LineAddToModal").on("keyup", "#Discount", function () {
  var value = $(this).val();
  if (!!value && !$(this).val().match(/^[0-9]*$/)) {
    $(this).val(preValueA);
    return false;
  }
  preValueA = $(this).val();
  return true;
});
//商城金额
$("#LineAddToModal").on("keyup", "#discountA", function () {
  var value = $(this).val();
    if(value==''){
        $(this).val('')
        return false
    }
  if (!!value && !$(this).val().match(/^[0-9]*$/)) {
    $(this).val(preValueA);
    return false;
  }
  preValueA = $(this).val();
  return true;
});
var zeroingObject=0//定义重复点击的变量
$('#addButtonS').on('click', '#LineSubmitForm', function () {
    //判断内容是否输入
  if (file.checkform('#formB')) {
    return false
  }
  //判断是否有付款方式

  if ($('input[name="payMethod"]').is(':checked') != true) {
    layer.msg('请选择付款方式', {icon: 5})
    return false
  }
  //判断优惠方式内容是否填写
  if ($("input[name='couponStatus']:checked").val() == 1) {
    if ($("input[name='voucherCode']").val() == '') {
      layer.msg('请填写优惠卷', {icon: 5})
      return false
    }
    if ($("input[name='voucherPriceStr']").val() == '') {
      layer.msg('请填写优惠金额', {icon: 5})
      return false
    }
  }
  //判断微商城商品是否填写
  if ($("input[name='couponStatus']:checked").val() == 2) {
    if ($("input[name='wechatMallName']").val() == '') {
      layer.msg('请填写商品名', {icon: 5})
      return false
    }
    if ($("input[name='wechatMallOrder']").val() == '') {
      layer.msg('请填写订单号', {icon: 5})
      return false
    }
    if ($("input[name='wechatMallPriceStr']").val() == '') {
      layer.msg('请填写金额', {icon: 5})
      return false
    }
  }
  //判断谈单人是否填写
    if ($("#talkOrderId").val() == '') {
        layer.msg('请选择单谈人', {icon: 5})
        return false
    }
  //是否选择服务
  if ($('#LineOrderPlaceB tr').length <= 1) {
    layer.msg('请选择最少一条服务', {icon: 5})
    return false
  }
  //首期费用不能为空
  var downpayment = $(".downpayment")
  for (var i = 0; i < downpayment.length; i++) {
    if (downpayment[i].value == '') {
      layer.msg('请填写首期费用', {icon: 5})
      return false
    }
  }
  //数量不能为空
  var subtractA = $(".subtractA")
  for (var i = 0; i < subtractA.length; i++) {
    if (subtractA[i].value == '') {
      layer.msg('请填写数量', {icon: 5})
      return false
    }
  }
  //系列不能为空
  var subtractB = $(".subtractB")
  for (var i = 0; i < subtractB.length; i++) {
    if (subtractB[i].value == '') {
      layer.msg('请填写系列数', {icon: 5})
      return false
    }
  }
  //防止重复点击提交
    if (zeroingObject == 0) {
        zeroingObject = 1;
        setTimeout(function () { zeroingObject = 0 }, 3000);
    }
    else{
        return false
    }
  var formB = $('#formB').serializeArray()
  var form = {}
  for (var i = 0; i < formB.length; i++) {
    form[formB[i].name] = formB[i].value
  }
  var api = Api.offlineOrderApi.addOrUpdate;
  var els = $('#formA').find(".fods");
  var strline = [];
  for (var i = 0; i < els.length; i++) {
    var rowItem = els[i];
    var tagInfo = new TagInfo(rowItem, "input", "name", "value");
    var params = scanParamsByModelName(tagInfo, api.model.strline[0]);
    strline.push(params)
  }
  console.log(strline)
  var remark = $('#Hremark').val()
  form.strline = strline
  form.remark = remark
  form.contractUrl = $(this).attr('data-address')
  if ($('#orderSearch').val() == '') {
    $.get('/customer/queryKVList', function (data) {
      if (data.code == 9999) {
        // debugger
        layer.msg(data.msg, {time: 1000});
        wzERP.Common.TimeoutLogin();
        return false;
      }
      var name = $('#custId').val()
      var val
      for (var i = 0; i < data.data.length; i++) {
        if (data.data[i].value == name) {
          val = data.data[i].key
        }
      }
      if (val == undefined) {
        layer.msg('客户不存在', {icon: 5})
        return false
      }
      form.custId = val
      NetUtis.doPostBody(api, form, function (data) {
        if (data.code == 0) {
          layer.msg('保存成功', {icon: 7})
          $('#LineAddToModal').modal('hide')
          //获取客户ID
          $.get('/customer/queryKVList', function (data) {
            if ($('#customerContent').val() != '') {
              var val
              var name = $('#customerContent').val()
              for (var i = 0; i < data.data.length; i++) {
                if (data.data[i].value == name) {
                  val = data.data[i].key
                }
              }
            } else {
              var val = null
            }
            var timeA = timeS()
            //获取当前每页应该显示条数
            queryS(timeA.page, timeA.num, timeA.searchKey, timeA.startDate,
                timeA.endDate, val)
          })
        }
        else if (data.code == 9999) {
          // debugger
          layer.msg(data.msg, {time: 1000});
          wzERP.Common.TimeoutLogin();
        }
        else {
          layer.msg('保存失败', {icon: 5})
        }
      }, true)
    })
  } else {
    $.get('/order/contract/queryKVList',
        {searchKey: $('#orderSearch').val()}, function (data) {
          if (data.code == 9999) {
            // debugger
            layer.msg(data.msg, {time: 1000});
            wzERP.Common.TimeoutLogin();
            return false;
          }
          if (data.data.length == 0) {
            layer.msg('订单编号有误', {icon: 5})
            return false
          }
          $.get('/customer/queryKVList', function (data) {
            var name = $('#custId').val()
            var val
            for (var i = 0; i < data.data.length; i++) {
              if (data.data[i].value == name) {
                val = data.data[i].key
              }
            }
            if (val == undefined) {
              layer.msg('客户不存在', {icon: 5})
              return false
            }
            form.custId = val
            NetUtis.doPostBody(api, form, function (data) {
              if (data.code == 0) {
                layer.msg('保存成功', {icon: 7})
                // wzERP.Common.delayReload(1000)
                $('#LineAddToModal').modal('hide')
                //获取客户ID
                $.get('/customer/queryKVList', function (data) {
                  if ($('#customerContent').val() != '') {
                    var val
                    var name = $('#customerContent').val()
                    for (var i = 0; i < data.data.length; i++) {
                      if (data.data[i].value == name) {
                        val = data.data[i].key
                      }
                    }
                  } else {
                    var val = null
                  }
                  var timeA = timeS()
                  //获取当前每页应该显示条数
                  queryS(timeA.page, timeA.num, timeA.searchKey,
                      timeA.startDate, timeA.endDate, val)
                })
              }
              else if (data.code == 9999) {
                // debugger
                layer.msg(data.msg, {time: 1000});
                wzERP.Common.TimeoutLogin();
              }
              else {
                layer.msg('保存失败', {icon: 5})
              }
            }, true)
          })
        })
  }
  return false
})

//关闭选择服务弹窗
$('#LineDisappear').on('click', function () {
  $('#LineSelectionService').css('display', 'none')
})
//关闭选择服务弹窗
$('#LineClose').on('click', function () {
  $('#LineSelectionService').css('display', 'none')
})

//订单详情主订单
$('#LinelistAreaData').on('click', '.LineDetails', function () {
  $('#LineDetailsToModal').modal({
    closable: false,
    transition: 'fade'
  }).modal('show')
  var id = $(this).attr('data-id')
  $('#auditContent').empty()
  details(id, '#LineOrderDetails', null, '#detailsButton')
})
//订单详情分订单
$('#LinelistAreaData').on('click', '.splitOrder', function () {
  $('#LineDetailsToModal').modal({
    closable: false,
    transition: 'fade'
  }).modal('show')
  var id = $(this).attr('data-id')
  $.get('/order/offline/detail', {id: id}, function (data) {
    if (data.code == -1) {
      layer.msg('服务器出错', {icon: 5})
      return false
    }
    else if (data.code == 9999) {
      // debugger
      layer.msg(data.msg, {time: 1000});
      wzERP.Common.TimeoutLogin();
      return false;
    }
    $('#LineOrderDetails').html(template('splitOrder', data.data))
    $('#detailsButton').html(
        '<section class="ui deny inverted blue button">取消</section>')
    //循环添加数量
    var quantityAnd = 0
    var Total = 0
    $('.singleOrderQuantityA').each(function () {
      quantityAnd += (+($(this).text()))
    });
    $('.splitTotal').text(quantityAnd)
    //成本总价
    $('.splitCostTotal').each(function () {
      //数量
      var num = $(this).siblings('.singleOrderQuantityA').text()
      //成本价
      var costPrice = $(this).siblings('.splitCost').text()
      //系列数
      var seriesNumd = $(this).siblings('.separateSeries').text()
      //附加成本
      var additionalCostW = $(this).attr('data-cost') / 100
      //附加市场价
      var additionalMarketPriceW = $(this).attr('data-price') / 100
      //附加官费
      var additionalOfficialExpensesW = $(this).attr('data-expenses') / 100
      //计算成本总价
      var total = num * (costPrice + ((+additionalOfficialExpensesW)
          + (+additionalCostW) + (+additionalMarketPriceW)) * (seriesNumd - 1))
      $(this).text(total)
    });
    //循环添加成本总价
    $('.splitCostTotal').each(function () {
      Total += (+($(this).text()))
    });
    $('.totalCostPerShare').text(Total)
  })
})
function details(id, el, es, em) {
  $.get('/order/offline/detail', {id: id}, function (data) {
    if (data.code == -1) {
      layer.msg('服务器出错', {icon: 5})
      return false
    }
    else if (data.code == 9999) {
      // debugger
      layer.msg(data.msg, {time: 1000});
      wzERP.Common.TimeoutLogin();
      return false;
    }
    $(el).html(template('orderDetails', data.data))
    console.log(data)
    if (es != null) {
      $(es).html(template('auditButton', data.data))
    }
    if (em != null) {
      $(em).html(template('preview', data.data))
    }
    var sval = $('input[name="preferentialWay"]:checked').val()
    if (sval == 1) {
      $('#disDetails').addClass("coupon")
      $('#mallDetails').addClass("coupon")
    } else if (sval == 0) {
      $('#disDetails').removeClass("coupon")
      $('#mallDetails').addClass("coupon")
    } else if (sval == 2) {
      $('#disDetails').addClass("coupon")
      $('#mallDetails').removeClass("coupon")
    }
    var detai = 0
    var total = 0
    var details = 0
    $('.detailQuantityA').text(0)
    $('.totalParticularsA').text(0)
    $('.detailsDownA').text(0)
    $('.detailQuantity').each(function () {
      detai += (+($(this).text()))
    });
    $('.totalParticulars').each(function () {
      total += (+($(this).text()))
    });
    $('.detailsDown').each(function () {
      details += (+($(this).text()))
    });
    //数量
    $('.detailQuantityA').text(detai)
    //总价
    $('.totalParticularsA').text(total)
    //首期费用总额
    $('.detailsDownA').text(details)
  })
}
// 定义模板过滤函数
template.defaults.imports.dateFormat = function (date) {
  return date / 100
};
template.defaults.imports.dateTime = function (time) {
  /*Arg Guide
   @ time 时间辍
   */
  if (time == null) {
    return
  } else {
    var date = new Date(time);
    return date.getFullYear() + '-' + (date.getMonth() + 1) + '-'
        + date.getDate();
  }
};
template.defaults.imports.dateTimes = function (now) {
  if (now == null) {
    return ''
  }
  function add0(m) {
    return m < 10 ? '0' + m : m
  }

  var time = new Date(now);
  var y = time.getFullYear();
  var m = time.getMonth() + 1;
  var d = time.getDate();
  var h = time.getHours();
  var mm = time.getMinutes();
  var s = time.getSeconds();
  return y + '-' + add0(m) + '-' + add0(d) + ' ' + add0(h) + ':' + add0(mm)
      + ':' + add0(s);
}
//编辑订单
$('#LinelistAreaData').on('click', '.LineEdit', function () {
  $('#LineOrderPlaceB .addRows').remove()
  $('#LineAddToModal').modal({
    closable: false,
    transition: 'fade'
  }).modal('show')
  var id = $(this).attr('data-id')
  $('#transformation').text('编辑订单')
  //获取客户名称
  $.get('/customer/queryKVList', function (dataA) {
    if (dataA.code == 9999) {
      // debugger
      layer.msg(dataA.msg, {time: 1000});
      wzERP.Common.TimeoutLogin();
      return false;
    }
    var customer = dataA.data
    //获取签单人
    $.get('/account/queryAccountDetail', function (data) {
      if (data.code == 9999) {
        // debugger
        layer.msg(data.msg, {time: 1000});
        wzERP.Common.TimeoutLogin();
        return false;
      }
      //获取当前公司ID
      var companyId = data.data.companyId
      //获取当前公司人员
      $.get('/basedata/employee/queryListByCompayID',
          {companyId: companyId}, function (dataB) {
            if (dataB.code == 9999) {
              // debugger
              layer.msg(dataB.msg, {time: 1000});
              wzERP.Common.TimeoutLogin();
              return false;
            }
            var order = dataB.data
            wzERP.Common.singleDate('#date3')
            //线下订单详情
            $.get('/order/offline/detail', {id: id}, function (dataC) {
              if (dataC.code == -1) {
                layer.msg('服务器出错', {icon: 5})
                return false
              }
              else if (dataC.code == 9999) {
                // debugger
                layer.msg(dataC.msg, {time: 1000});
                wzERP.Common.TimeoutLogin();
                return false;
              }
              var echo = dataC.data
              for (var i = 0; i < customer.length; i++) {
                customer[i].custId = echo.custId
              }
              for (var i = 0; i < order.length; i++) {
                order[i].signId = echo.signId
                order[i].talkId = echo.talkId
              }
              var dataA = {
                customer: customer,
                order: order,
              }
              for (var key in echo) {
                dataA[key] = echo[key]
              }
              var data = dataA.odlist
              dataA.data = data
              $('#LineOrderPlaceA').html(template('LineAddTemplate', dataA))
              $('.remarksFill').html(template('addRemarks', dataA))
              $('#LineOrderPlaceB').prepend(
                  template('LineAddFormTemplate', dataA))
              $('#addButtonS').html(template('editButton', dataA))
              file.verifier('#LineOrderPlaceA .file-verifier');
              console.log(dataA)
              $('#LineOrderPlaceA #signOrderId').dropdown('restore defaults')
              $('#LineOrderPlaceA #talkOrderId').dropdown('restore defaults')
              wzERP.Common.singleDate('#date3')
              $('#clickA').on('click', function () {
                $('.addRows').remove()
              })
              $('#editCancel').on('click', function () {
                $('.addRows').remove()
              })
              $('#LineOrderPlaceB .addRows')
              var sval = $('input[name="couponStatus"]:checked').val()
              if (sval == 0) {
                $('#coupon').addClass("coupon")
                $('#wechat').addClass("coupon")
              } else if (sval == 1) {
                $('#coupon').removeClass("coupon")
                $('#wechat').addClass("coupon")
              } else if (sval == 2) {
                $('#coupon').addClass("coupon")
                $('#wechat').removeClass("coupon")
              }
              //判断优惠方式
              $('input[name="couponStatus"]').on('click', function () {
                var sval = $('input[name="couponStatus"]:checked').val()
                if (sval == 0) {
                  $('#coupon').addClass("coupon")
                  $('#wechat').addClass("coupon")
                } else if (sval == 1) {
                  $('#coupon').removeClass("coupon")
                  $('#wechat').addClass("coupon")
                } else if (sval == 2) {
                  $('#coupon').addClass("coupon")
                  $('#wechat').removeClass("coupon")
                }
              })
              //删除按钮
              $('#LineOrderPlaceA').on('click', '#delDT', function () {
                if ($('tr input[name="boxA"]:checked').length == $(
                        'tr input[name="boxA"]').length) {
                  layer.msg('不能全部删除，请至少保留一条数据', {icon: 5})
                } else {
                  $('tr input[name="boxA"]:checked').parents('.fods').remove();
                }
                calculationA()
                //循环首期费用
                var downpayment = 0
                $('.downpayment').each(function () {
                  downpayment += (+($(this).val()))
                })
                $('#paymentNum').text(downpayment)
              })

              //计算
              calculationA()
              function calculationA() {
                var quantityAnd = 0
                var Total = 0
                //循环添加数量
                $('#LineOrderPlaceB .subtractA').each(function () {
                  quantityAnd += (+($(this).val()))
                });
                //循环添加总价
                $('#LineOrderPlaceB #aggregate').each(function () {
                  Total += (+($(this).text()))
                });
                //优惠金额
                var Discount = $('#Discount').val() != 'null' ? $(
                    '#Discount').val() : 0
                //微商城金额
                var discountA = $('#discountA').val() != 'null' ? $(
                    '#discountA').val() : 0

                //计算订单总额
                var num = Total - Discount - discountA
                //添加合计数量
                $('#quantityAnd').text(quantityAnd)
                //添加合计总价
                $('#Total').text(Total)
                //添加订单总额
                $('#LineOrderPlaceA #totalOrder').text(num)
                //数量变化时的总价
                $('#LineOrderPlaceB').on('change', '.subtractA', function () {
                  //获取数量
                  var numZ = $(this).val()
                  //获取系列
                  var seriesZ = $(this).parent().next().children(
                      ".subtractB").val()
                  //附加成本
                  var additionalCost = $(this).attr('data-cost') / 100
                  //附加市场价
                  var additionalMarketPrice = $(this).attr('data-price') / 100
                  //附加官费
                  var additionalOfficialExpenses = $(this).attr('data-expenses')
                      / 100
                  //单价
                  var marketPriceZ = $(this).attr('data-priceA') / 100
                  //判断是否有系列数
                  var judge = $(this).attr('data-judge')
                  //获取有系列数的原价
                  var originalPrice = $(this).attr('data-originalPrice') / 100
                  //当单价有系列数的时候
                  if (judge != '') {
                    //渲染单价
                    $(this).parent().siblings('.nnitSeries').text(
                        originalPrice + ((+additionalCost)
                        + (+additionalMarketPrice)
                        + (+additionalOfficialExpenses)) * (seriesZ - 1))
                    //计算总价
                    var totalZ = numZ * (originalPrice + ((+additionalCost)
                        + (+additionalMarketPrice)
                        + (+additionalOfficialExpenses)) * (seriesZ - 1))
                    //当单价没有系列数的时候
                  } else if (judge == '') {
                    //渲染单价
                    $(this).parent().siblings('.nnitSeries').text(
                        marketPriceZ + ((+additionalCost)
                        + (+additionalMarketPrice)
                        + (+additionalOfficialExpenses)) * (seriesZ - 1))
                    //计算总价
                    var totalZ = numZ * (marketPriceZ + ((+additionalCost)
                        + (+additionalMarketPrice)
                        + (+additionalOfficialExpenses)) * (seriesZ - 1))
                  }
                  $(this).parent().siblings('#aggregate').text(totalZ)
                  var quantityAndZ = 0
                  var TotalZ = 0
                  //循环添加数量
                  $('#LineOrderPlaceB .subtractA').each(function () {
                    quantityAndZ += (+($(this).val()))
                  });
                  //循环添加总价
                  $('#LineOrderPlaceB #aggregate').each(function () {
                    TotalZ += (+($(this).text()))
                  });
                  //优惠金额
                  var DiscountZ = $('#Discount').val() != 'null' ? $(
                      '#Discount').val() : 0
                  //微商城金额
                  var discountAZ = $('#discountA').val() != 'null' ? $(
                      '#discountA').val() : 0
                  //计算订单总额
                  var numZ = TotalZ - DiscountZ - discountAZ
                  //添加合计数量
                  $('#quantityAnd').text(quantityAndZ)
                  //添加合计总价
                  $('#Total').text(TotalZ)
                  //添加订单总额
                  $('#LineOrderPlaceA #totalOrder').text(numZ)
                })
                //系列变化时的总价
                $('#LineOrderPlaceB').on('change', '.subtractB', function () {
                  //获取系列
                  var numW = $(this).val()
                  //获取数量
                  var seriesW = $(this).parent().prev().children(
                      ".subtractA").val()
                  //附加成本
                  var additionalCostW = $(this).attr('data-cost') / 100
                  //附加市场价
                  var additionalMarketPriceW = $(this).attr('data-price') / 100
                  //附加官费
                  var additionalOfficialExpensesW = $(this).attr(
                          'data-expenses') / 100
                  //单价
                  var marketPriceW = $(this).attr('data-priceA') / 100
                  //判断是否有系列数
                  var judge = $(this).attr('data-judge')
                  //获取有系列数的原价
                  var originalPrice = $(this).attr('data-originalPrice') / 100
                  //当单价有系列数的时候
                  if (judge != '') {
                    //渲染单价
                    $(this).parent().siblings('.nnitSeries').text(
                        originalPrice + ((+additionalCostW)
                        + (+additionalMarketPriceW)
                        + (+additionalOfficialExpensesW)) * (numW - 1))
                    //计算总价
                    var totalW = seriesW * (originalPrice + ((+additionalCostW)
                        + (+additionalMarketPriceW)
                        + (+additionalOfficialExpensesW)) * (numW - 1))
                    //当单价没有系列数的时候
                  } else if (judge == '') {
                    //渲染单价
                    $(this).parent().siblings('.nnitSeries').text(
                        marketPriceW + ((+additionalCostW)
                        + (+additionalMarketPriceW)
                        + (+additionalOfficialExpensesW)) * (numW - 1))
                    //计算总价
                    var totalW = seriesW * (marketPriceW + ((+additionalCostW)
                        + (+additionalMarketPriceW)
                        + (+additionalOfficialExpensesW)) * (numW - 1))
                  }
                  $(this).parent().siblings('#aggregate').text(totalW)
                  var quantityAndW = 0
                  var TotalW = 0
                  //循环添加数量
                  $('#LineOrderPlaceB .subtractA').each(function () {
                    quantityAndW += (+($(this).val()))
                  });
                  //循环添加总价
                  $('#LineOrderPlaceB #aggregate').each(function () {
                    TotalW += (+($(this).text()))
                  });
                  //优惠金额
                  var DiscountW = $('#Discount').val() != 'null' ? $(
                      '#Discount').val() : 0
                  //微商城金额
                  var discountAW = $('#discountA').val() != 'null' ? $(
                      '#discountA').val() : 0
                  //计算订单总额
                  var numW = TotalW - DiscountW - discountAW
                  //添加合计数量
                  $('#quantityAnd').text(quantityAndW)
                  //添加合计总价
                  $('#Total').text(TotalW)
                  //添加订单总额
                  $('#LineOrderPlaceA #totalOrder').text(numW)
                })
                //计算首期费用
                $('#LineOrderPlaceB').on('change', '.downpayment', function () {
                  //循环首期费用
                  var downpayment = 0
                  $('.downpayment').each(function () {
                    downpayment += (+($(this).val()))
                  })
                  $('#paymentNum').text(downpayment)
                })
                var downpayment = 0
                $('.downpayment').each(function () {
                  downpayment += (+($(this).val()))
                })
                $('#paymentNum').text(downpayment)
              }
            })
          })
    })
  })
  linkage()
  select()
  notAll()
  Total()
})
//编辑订单方法
//提交合同
$('#addButtonS').on('change', '#editFile', function () {
  if (!$('#editFile').val().endsWith('pdf')) {
    layer.msg('合同格式错误', {icon: 5})
    return false
  }
  var id = $(this).attr('data-id')
  $('#editfiles').ajaxSubmit({
    data: {type: 1},
    success: function (data) {
      if (data.code == 0) {
        var contractUrl = data.data.filePath
        $.post('/order/offline/contactUpload',
            {contractUrl: data.data.filePath, id: id}, function (data) {
              if (data.code == 0) {
                layer.msg('上传成功', {icon: 7})
                data.id = id
                data.contractUrl = contractUrl
                $('#addButtonS').html(template('editButton', data))
                $('#clickA').on('click', function () {
                  //获取客户ID
                  $.get('/customer/queryKVList', function (data) {
                    if (data.code == 9999) {
                      // debugger
                      layer.msg(data.msg, {time: 1000});
                      wzERP.Common.TimeoutLogin();
                      return false;
                    }
                    if ($('#customerContent').val() != '') {
                      var val
                      var name = $('#customerContent').val()
                      for (var i = 0; i < data.data.length; i++) {
                        if (data.data[i].value == name) {
                          val = data.data[i].key
                        }
                      }
                    } else {
                      var val = null
                    }
                    var timeA = timeS()
                    //获取当前每页应该显示条数
                    queryS(timeA.page, timeA.num, timeA.searchKey,
                        timeA.startDate, timeA.endDate, val)
                  })
                })
                $('#editCancel').on('click', function () {
                  //获取客户ID
                  $.get('/customer/queryKVList', function (data) {
                    if (data.code == 9999) {
                      // debugger
                      layer.msg(data.msg, {time: 1000});
                      wzERP.Common.TimeoutLogin();
                      return false;
                    }
                    if ($('#customerContent').val() != '') {
                      var val
                      var name = $('#customerContent').val()
                      for (var i = 0; i < data.data.length; i++) {
                        if (data.data[i].value == name) {
                          val = data.data[i].key
                        }
                      }
                    } else {
                      var val = null
                    }
                    var timeA = timeS()
                    //获取当前每页应该显示条数
                    queryS(timeA.page, timeA.num, timeA.searchKey,
                        timeA.startDate, timeA.endDate, val)
                  })
                })
              }
              else if (data.code == 9999) {
                // debugger
                layer.msg(data.msg, {time: 1000});
                wzERP.Common.TimeoutLogin();
                return false;
              }
              else {
                layer.msg('上传失败', {icon: 5})
              }
            })
      }
      else if (data.code == 9999) {
        // debugger
        layer.msg(data.msg, {time: 1000});
        wzERP.Common.TimeoutLogin();
      }
      else {
        layer.msg('上传失败', {icon: 5})
      }
    }
  })
})
//编辑添加订单内容
var editOrders=0//定义重复点击的变量
$('#addButtonS').on('click', '#editSave', function () {
  //判断内容是否输入
  if (file.checkform('#formB')) {
    return false
  }
  //判断优惠方式内容是否填写
  if ($("input[name='couponStatus']:checked").val() == 1) {
    if ($("input[name='voucherCode']").val() == '') {
      layer.msg('请填写优惠卷', {icon: 5})
      return false
    }
    if ($("input[name='voucherPriceStr']").val() == '') {
      layer.msg('请填写优惠金额', {icon: 5})
      return false
    }
  }
  //判断微商城商品是否填写
  if ($("input[name='couponStatus']:checked").val() == 2) {
    if ($("input[name='wechatMallName']").val() == '') {
      layer.msg('请填写商品名', {icon: 5})
      return false
    }
    if ($("input[name='wechatMallOrder']").val() == '') {
      layer.msg('请填写订单号', {icon: 5})
      return false
    }
    if ($("input[name='wechatMallPriceStr']").val() == '') {
      layer.msg('请填写金额', {icon: 5})
      return false
    }
  }
  //首期费用不能为空
  var downpayment = $(".downpayment")
  for (var i = 0; i < downpayment.length; i++) {
    if (downpayment[i].value == '') {
      layer.msg('请填写首期费用', {icon: 5})
      return false
    }
  }
  //数量不能为空
  var subtractA = $(".subtractA")
  for (var i = 0; i < subtractA.length; i++) {
    if (subtractA[i].value == '') {
      layer.msg('请填写数量', {icon: 5})
      return false
    }
  }
  //系列不能为空
  var subtractB = $(".subtractB")
  for (var i = 0; i < subtractB.length; i++) {
    if (subtractB[i].value == '') {
      layer.msg('请填写系列数', {icon: 5})
      return false
    }
  }
//防止重复点击提交
    if (editOrders == 0) {
        editOrders = 1;
        setTimeout(function () { editOrders = 0 }, 3000);
    }
    else{
        return false
    }
  var orderCode = $('#orderSearch').val()
  var formB = $('#formB').serializeArray()
  var form = {}
  var id = $(this).attr('data-id')
  for (var i = 0; i < formB.length; i++) {
    form[formB[i].name] = formB[i].value
  }
  var api = Api.offlineOrderApi.update;
  var els = $('#formA').find(".fods");
  var strline = [];
  for (var i = 0; i < els.length; i++) {
    var rowItem = els[i];
    var tagInfo = new TagInfo(rowItem, "input", "name", "value");
    var params = scanParamsByModelName(tagInfo, api.model.strline[0]);
    strline.push(params)
  }
  var remark = $('.Hremark').val()
  console.log(remark)
  form.strline = strline
  form.remark = remark
  form.id = id
  form.orderCode = orderCode
  if (form.signOrderDate == '') {
    form.signOrderDate = $('.timeS').attr('data-end')
  }
  $.get('/customer/queryKVList', function (data) {
    if (data.code == 9999) {
      // debugger
      layer.msg(data.msg, {time: 1000});
      wzERP.Common.TimeoutLogin();
      return false;
    }
    var name = $('#custId').val()
    var val
    for (var i = 0; i < data.data.length; i++) {
      if (data.data[i].value == name) {
        val = data.data[i].key
      }
    }
    if (val == undefined) {
      layer.msg('客户不存在', {icon: 5})
      return false
    }
    form.custId = val
    NetUtis.doPostBody(api, form, function (data) {
      if (data.code == 0) {
        layer.msg('保存成功', {icon: 7})
        $('#LineAddToModal').modal('hide')
        //获取客户ID
        $.get('/customer/queryKVList', function (data) {
          if ($('#customerContent').val() != '') {
            var val
            var name = $('#CustomerContent').val()
            for (var i = 0; i < data.data.length; i++) {
              if (data.data[i].value == name) {
                val = data.data[i].key
              }
            }
          } else {
            var val = null
          }
          var timeA = timeS()
          //获取当前每页应该显示条数
          queryS(timeA.page, timeA.num, timeA.searchKey, timeA.startDate,
              timeA.endDate, val)
        })
      }
      else if (data.code == 9999) {
        // debugger
        layer.msg(data.msg, {time: 1000});
        wzERP.Common.TimeoutLogin();
      }
      else {
        layer.msg('保存失败', {icon: 5})
      }
    }, true)
  })
  return false
})

//审核订单
//审核说明的必填内容
$('#audited').on('change',function () {
    if ($('#audited').val() == 1 || $('#audited').val() == 0) {
        $("#auditeas").removeClass("required")
    }
    if ($('#audited').val() == 2) {
        $("#auditeas").addClass("required")
    }
})
$('#LinelistAreaData').on('click', '.LineExamine', function () {
  $('#LineExamineToModal').modal({
    closable: false,
    transition: 'fade'
  }).modal('show')
  var id = $(this).attr('data-id')
  $('#LineOrderDetails').empty()
  details(id, '#auditContent', '#auditPlacement')
    //清空上次遗留下来的数据
    $('#audited').val(0)//审核状态
    $('#modalsa .text').text('请选择')
    $("#auditeas").removeClass("required")
    $('#descriptexamine').val('')//备注

})
var auditOrders=0//定义重复点击的变量
$('#auditPlacement').on('click', '.submitAnAudit', function () {
  var id = $(this).attr('data-id')
  if ($('#audited').val() == 0) {
    layer.msg('请选择审核结果', {icon: 5})
    return false
  }
  if ($('#audited').val() == 2) {
    if ($('#descriptexamine').val() == '') {
      layer.msg('请在备注中说明不通过原因！', {icon: 5})
      return false
    }
  }
  var status = $('#audited').val()
  var descript = $('#descriptexamine').val()
    //防止重复点击提交
    if (auditOrders == 0) {
        auditOrders = 1;
        setTimeout(function () { auditOrders = 0 }, 3000);
    }
    else{
        return false
    }
  $.post('/order/offline/audit',
      {id: id, status: status, descript: descript}, function (data) {
        if (data.code == 0) {
          layer.msg('提交成功', {icon: 7})
          $('#LineExamineToModal').modal('hide')
          //获取客户ID
          $.get('/customer/queryKVList', function (data) {
            if ($('#customerContent').val() != '') {
              var val
              var name = $('#customerContent').val()
              for (var i = 0; i < data.data.length; i++) {
                if (data.data[i].value == name) {
                  val = data.data[i].key
                }
              }
            } else {
              var val = null
            }
            var timeA = timeS()
            //获取当前每页应该显示条数
            queryS(timeA.page, timeA.num, timeA.searchKey, timeA.startDate,
                timeA.endDate, val)
          })
        }
        else if (data.code == 9999) {
          // debugger
          layer.msg(data.msg, {time: 1000});
          wzERP.Common.TimeoutLogin();
        }
        else {
          layer.msg('提交失败', {icon: 5})
        }
      })
})

//分单
$('#LinelistAreaData').on('click', '.LinePolicy', function () {
  $('#LinePolicyToModal').modal({
    closable: false,
    transition: 'fade'
  }).modal('show')
  var id = $(this).attr('data-id')
  $.get('/order/offline/detail', {id: id}, function (data) {
    if (data.code == 9999) {
      // debugger
      layer.msg(data.msg, {time: 1000});
      wzERP.Common.TimeoutLogin();
      return false;
    }
    var content = data
    console.log(data)

    NetUtis.doGetSimple('/basedata/company/queryCompanyList',
        {excludeSelfCompany: 1}, function (data) {
          var contentObj = {
            content: content.data,
            data: data.data
          }
          console.log(contentObj)
          $('#LinePolicyToModal').html(
              template('reinsuranceTemplate', contentObj))
          //循环添加数量
          var quantityAnd = 0
          var Total = 0
          $('.singleOrderQuantity').each(function () {
            quantityAnd += (+($(this).text()))
          });
          $('.singleOrderA').text(quantityAnd)
          //成本总价
          $('.costTotal').each(function () {
            //数量
            var num = $(this).siblings('.singleOrderQuantity').text()
            //成本价
            var costPrice = $(this).siblings('.costPriced').text()
            //系列数
            var seriesNumd = $(this).siblings('.seriesNumd').text()
            //附加成本
            var additionalCostW = $(this).attr('data-cost') / 100
            //附加市场价
            var additionalMarketPriceW = $(this).attr('data-price') / 100
            //附加官费
            var additionalOfficialExpensesW = $(this).attr('data-expenses')
                / 100
            //计算成本总价
            var total = num * costPrice + ((+additionalOfficialExpensesW)
                + (+additionalCostW) + (+additionalMarketPriceW)) * (seriesNumd
                - 1)
            $(this).text(total)
          });
          // 计算分单订单总额
          $('input[name="reinsurancePolicyId"]').on('click', function () {
            var numDd = 0
            $('input[name="reinsurancePolicyId"]:checked').each(function () {
              numDd += (+$(this).parent().parent().siblings(
                  ".costTotal").text())
            });
            $('.ddze').text(numDd)
          })

          //循环添加成本总价
          $('.costTotal').each(function () {
            Total += (+($(this).text()))
          });
          $('.costTotald').text(Total)
        }, true);
  })

})
var reinsurancePolicys=0//定义重复点击的变量
$('#LinePolicyToModal').on('click', '.submitAseparateOrder', function () {
  if ($('#companyCode').val() == 'as123') {
    layer.msg('请选择接单公司', {icon: 5})
    return false
  }
  if ($('input[name="reinsurancePolicyId"]:checked').length < 1) {
    layer.msg('请选择服务', {icon: 5})
    console.log($('input[name="reinsurancePolicyId"]:checked').length)
    return false
  }
  var companyCode = $('#companyCode').val()
  var orderCode = $('#orderNumber').text()
  var dids = []

  $('input[name="reinsurancePolicyId"]:checked').each(function () {
    dids.push($(this).val())
  });
    //防止重复点击提交
    if (reinsurancePolicys == 0) {
        reinsurancePolicys = 1;
        setTimeout(function () { reinsurancePolicys = 0 }, 3000);
    }
    else{
        return false
    }
  NetUtis.doPostBodySimple('/order/offline/distribute',
      {receiveCompanyCode: companyCode, orderCode: orderCode, dids: dids},
      function (data) {
        if (data.code == 0) {
          layer.msg('提交成功', {icon: 7})
          $('#LinePolicyToModal').modal('hide')
          //获取客户ID
          $.get('/customer/queryKVList', function (data) {
            if ($('#customerContent').val() != '') {
              var val
              var name = $('#customerContent').val()
              for (var i = 0; i < data.data.length; i++) {
                if (data.data[i].value == name) {
                  val = data.data[i].key
                }
              }
            } else {
              var val = null
            }
            var timeA = timeS()
            //获取当前每页应该显示条数
            queryS(timeA.page, timeA.num, timeA.searchKey, timeA.startDate,
                timeA.endDate, val)
          })
        }
        else if (data.code == 9999) {
          layer.msg(data.msg, {time: 1000});
          wzERP.Common.TimeoutLogin();
        }
        else {
          layer.msg('提交失败', {icon: 5})
        }
      }, true)
})
//删除订单
$('#LinelistAreaData').on('click', '.delSc', function () {
  var id = $(this).data('id');
  layer.alert('确定删除该订单吗？', {
        title: '提示信息',
        btn: ['取消', '确认'],
        btn1: function (index) {
          layer.close(index)
        },
        btn2: function () {
          $.post('/order/offline/delete', {id: id}, function (data) {
            if (data.code == 0) {
              layer.msg('删除成功', {icon: 1})
              //获取客户ID
              $.get('/customer/queryKVList', function (data) {
                if ($('#customerContent').val() != '') {
                  var val
                  var name = $('#customerContent').val()
                  for (var i = 0; i < data.data.length; i++) {
                    if (data.data[i].value == name) {
                      val = data.data[i].key
                    }
                  }
                } else {
                  var val = null
                }
                var timeA = timeS()
                //获取当前每页应该显示条数
                queryS(timeA.page, timeA.num, timeA.searchKey, timeA.startDate,
                    timeA.endDate, val)
              })
            }
            else if (data.code == 9999) {
              // debugger
              layer.msg(data.msg, {time: 1000});
              wzERP.Common.TimeoutLogin();
            }
            else {
              layer.msg('删除失败', {icon: 2})
            }
          })
        }
      }
  );

  /*$('#delAS').modal('show')
   var id = $(this).attr('data-id')
   $('.delH').attr('data-id',id)*/
})
/*$('.delH').on('click',function() {
 var id = $(this).attr('data-id')
 $.post('/order/offline/delete', {id: id}, function (data) {
 if (data.code == 0) {
 layer.msg('删除成功', {icon: 1})
 //获取客户ID
 $.get('/customer/queryKVList',function(data){
 if($('#customerContent').val()!=''){
 var val
 var name=$('#customerContent').val()
 for(var i=0;i<data.data.length;i++){
 if(data.data[i].value==name){
 val = data.data[i].key
 }
 }
 }else {
 var val = null
 }
 var timeA = timeS()
 //获取当前每页应该显示条数
 queryS(timeA.page,timeA.num,timeA.searchKey,timeA.startDate,timeA.endDate,val)
 })
 } else {
 layer.msg('删除失败', {icon: 2})
 }
 })
 })*/
//提交功能
$('#LinelistAreaData').on('click', '.SubmissionOfcontract', function () {
  var id = $(this).attr('data-id')
  $.post('/order/offline/submit', {id: id}, function (data) {
    if (data.code == 0) {
      layer.msg('提交成功', {icon: 7})
      //获取客户ID
      $.get('/customer/queryKVList', function (data) {
        if ($('#customerContent').val() != '') {
          var val
          var name = $('#customerContent').val()
          for (var i = 0; i < data.data.length; i++) {
            if (data.data[i].value == name) {
              val = data.data[i].key
            }
          }
        } else {
          var val = null
        }
        var timeA = timeS()
        //获取当前每页应该显示条数
        queryS(timeA.page, timeA.num, timeA.searchKey, timeA.startDate,
            timeA.endDate, val)
      })
    }
    else if (data.code == 9999) {
      // debugger
      layer.msg(data.msg, {time: 1000});
      wzERP.Common.TimeoutLogin();
    }
    else {
      layer.msg('提交失败', {icon: 5})
    }
  })
})
//立案
$('#LinelistAreaData').on('click', '.LineFiling', function () {
  var id = $(this).attr("data-id");
  var _this = $(this);
  $.get('/account/queryAccountDetail', function (data) {
    if (data.code == 9999) {
      // debugger
      layer.msg(data.msg, {time: 1000});
      wzERP.Common.TimeoutLogin();
      return false;
    }
    var opt = {
      // id:id,
      orderCode: _this.data('code'),
      _this: $(this),
      orderType: "0", //0线下 1 线上
      url: "/order/offline/detail",
      user_nickname: data.data.employName,
      pageSort: 'xx',
    }
    console.log(opt);
    case_build.pop(opt);
  })

  //$('#LineFilingToModal').modal('show')
})
//接单
$('#LinelistAreaData').on('click', '.LineOrders', function () {
  $('#LineOrdersToModal').modal({
    closable: false,
    transition: 'fade'
  }).modal('show')
  var id = $(this).attr('data-id')
  $.get('/order/offline/detail', {id: id}, function (data) {
    $('#orderContent').html(template('orderSheet', data.data))
    $('#submission').html(template('pressTheButton', data.data))
    var detai = 0
    var total = 0
    $('.totalOrder').text(0)
    $('.orderSum').text(0)
    $('.orderQuantity').each(function () {
      detai += (+($(this).text()))
    });
    $('.orderPrice').each(function () {
      total += (+($(this).text()))
    });
    //数量
    $('.totalOrder').text(detai)
    //成本总价
    $('.orderSum').text(total)
    $('.orderAmount').text(total)
  })
    //清空上次遗留的数据
    $('#auditResultForm').val(2)//上次的审核结果
    $('#statementOfReceiptS').val('')//上次的备注
})
//接单提交审核
var submissionofReceipt=0//定义重复点击的变量
$('#submission').on('click', '.submission', function () {
  if ($('#auditResultForm').val() == 0) {
    if ($('#statementOfReceiptS').val() == '') {
      layer.msg('请在备注中说明不通过原因！', {icon: 5})
      return false
    }
  }
  var orderCode = $(this).attr('data-id')
  if ($('#auditResultForm').val() == 2) {
    layer.msg('请选择审核结果', {icon: 5})
    return false
  }
  var status = $('#auditResultForm').val()
  var descript = $('#statementOfReceiptS').val()
    //防止重复点击提交
    if (submissionofReceipt == 0) {
        submissionofReceipt = 1;
        setTimeout(function () { submissionofReceipt = 0 }, 3000);
    }
    else{
        return false
    }
  $.post('/order/offline/confirm/receive',
      {orderCode: orderCode, agree: status, mark: descript}, function (data) {
        if (data.code == 0) {
          layer.msg('提交成功', {icon: 7})
          $('#LineOrdersToModal').modal('hide')
          //获取客户ID
          $.get('/customer/queryKVList', function (data) {
            if ($('#customerContent').val() != '') {
              var val
              var name = $('#customerContent').val()
              for (var i = 0; i < data.data.length; i++) {
                if (data.data[i].value == name) {
                  val = data.data[i].key
                }
              }
            } else {
              var val = null
            }
            var timeA = timeS()
            //获取当前每页应该显示条数
            queryS(timeA.page, timeA.num, timeA.searchKey, timeA.startDate,
                timeA.endDate, val)
          })
        }
        else if (data.code == 9999) {
          layer.msg(data.msg, {time: 1000});
          wzERP.Common.TimeoutLogin();
        }
        else {
          layer.msg('提交失败', {icon: 5})
        }
      })
})

